package 队列;

public class CirQueue implements IQueue{
    private  final int defaultSize=100;
    private  int maxSzie;
    int front;//对首(对首的前一个位置)
    int rear;//队尾
    Object[] data;

    public CirQueue(){
        initiate(defaultSize);
    }
    public CirQueue(int sz){
        initiate(sz);

    }
    private void initiate(int sz){
        this.maxSzie=sz;
        data = new Object[sz];
        front = rear=0;//初始化为空队
    }

    @Override
    public void append(Object obj) throws Exception {
        if(front==(rear+1%maxSzie)){
            throw new Exception("队满");
        }else{
            rear=(rear+1)%maxSzie;//队尾后移
            data[rear]=obj;//赋值
        }
    }

    @Override
    public Object delete() throws Exception {
        Object a;
        if(front==rear){
            return null;
        }else{
            a=data[(front+1)%maxSzie];//当前对首
            front=(front+1)%maxSzie;
            return a;
        }

    }

    @Override
    public Object getFront() throws Exception {
        if(front==rear) {
            return null;
        }else {
            return data[(front + 1) % maxSzie];
        }
    }

    @Override
    public boolean isEmpty() {
        return front==rear;
    }

    @Override
    public int size() {
        //队列长度
        return (rear-front+maxSzie)%maxSzie;
    }

    @Override
    public void print() {
        for (int i =front; i <rear; i=(i+1)%maxSzie) {
            System.out.print(data[(i+1)%maxSzie]+" ");
        }
        System.out.print(" ");
    }
    //队首入队
    public void appendIN(Object obj) throws Exception {
        if(front==(rear+1%maxSzie)){
            throw new Exception("队满");
        }else{
            data[front]=obj;//赋值
            front=(front-1+maxSzie)%maxSzie;
        }
    }
    //队尾出队
    public Object deleteOut() throws Exception {
        Object a;
        if(front==rear){
            return null;
        }else{
            a=data[rear];
            rear=(rear-1+maxSzie)%maxSzie;
            return a;
        }

    }
}
